package org.tao.lightningmq.nameserver.event.spi.listener;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.tao.lightningmq.common.enums.NameServerResponseCode;
import org.tao.lightningmq.common.event.Listener;
import org.tao.lightningmq.common.tcp.TcpMsg;
import org.tao.lightningmq.nameserver.common.CommonCache;
import org.tao.lightningmq.nameserver.event.model.StartReplicationEvent;

import java.net.InetSocketAddress;

/**
 * @Author lht
 * @date 2025/1/16 - 22:59
 * @description: 开启复制监听器
 */
public class StartReplicationListener implements Listener<StartReplicationEvent> {
    @Override
    public void onReceive(StartReplicationEvent event) throws Exception {
        ChannelHandlerContext context = event.getContext();
        if (!RegistryListener.isVerify(event.getUser(), event.getPassword())) {
            TcpMsg tcpMsg = new TcpMsg(NameServerResponseCode.ERROR_USER_OR_PASSWORD);
            context.writeAndFlush(tcpMsg);
            context.close();
            throw new IllegalAccessException("error account to connected!");
        }
        InetSocketAddress inetSocketAddress = (InetSocketAddress) context.channel().remoteAddress();
        String reqId = inetSocketAddress.getHostString() + ":" + inetSocketAddress.getPort();
        context.attr(AttributeKey.valueOf("reqId")).set(reqId);
        CommonCache.getReplicationChannelManager().put(reqId, context);
        context.writeAndFlush(new TcpMsg(NameServerResponseCode.MASTER_START_REPLICATION_ACK));
    }
}
